<template>

  <el-dialog v-model="openBoole" :close-on-click-modal="false" :lock-scroll="true" :title="title" append-to-body
    custom-class="mydialog" width="50%" @close="close">
    <el-form ref="openRef" :model="openForm" :rules="rules" class="dialogForm" label-width="110px" size="small">
      <el-row gutter="40" style="margin: 0">
        <template v-if="booleDis">
          <el-col :span="24">
            <item-title title="基础信息" />
          </el-col>
          <el-col :span="8">
            <el-form-item label="终端名称：" style="width: 100%;">
              <toolTip :title="queryParams.terminalName" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="终端价：" prop="terminalName">
              <span v-if="queryParams.terminalPrice > 0">{{ queryParams.terminalPrice }}元</span>
              <span v-if="sellUnit">
                /{{ getLabel('sell_unit', sellUnit) }}
              </span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="准入模式：" prop="terminalName">
              {{ getLabel('access_mode', queryParams.accessMode) }}
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="营销模式：" prop="terminalName" v-if="fineBool">
              <span v-if="queryParams.sellMode !== 'direct'">
                {{ queryParams.agentAttribute === '1' ? '区域招商' : '精细招商' }}
              </span>
              <span v-else> 终端直销</span>
            </el-form-item>
            <el-form-item label="终端类型：" v-else>
              <span>{{ getLabel('app_mode', queryParams.terminalType) }}</span>
            </el-form-item>

          </el-col>
          <el-col :span="8" v-if="queryParams?.agentName">
            <el-form-item label="代理名称：" style="width: 100%;">
              <toolTip :title="datas?.agentName" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="负责营销职员：" prop="terminalName">
              {{ queryParams.headName }}
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="产品信息：" prop="terminalName">
              {{ getProductName(queryParams.productInfoDetail ? queryParams.productInfoDetail : queryParams) }}
            </el-form-item>
          </el-col>
        </template>

        <template v-else>
          <el-col :span="24">
            <item-title title="基础信息" />
          </el-col>

          <el-col :span="24">
            <el-form-item label="产品信息：" prop="terminalName">
              {{ getProductName(queryParams.productInfoDetail ? queryParams.productInfoDetail : queryParams) }}
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="代理名称：" style="width: 100%;">
              <toolTip :title="datas?.agentName" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="代理地区：" label-width="110px">
              <area-list-view :areas="region" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="可营销终端：">
              {{ getLabel('app_mode', queryParams?.terminalType) }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责营销职员：" label-width="110px">
              {{ queryParams?.headName }}
            </el-form-item>
          </el-col>

        </template>

        <template v-if="queryParams?.distributeContractDetails.length >0">
          <el-col :span="24">
            <item-title title="已设置配送信息" />
          </el-col>
          <el-col :span="24">
            <el-table :data="queryParams?.distributeContractDetails" border class="tableForm"
              header-cell-class-name="table-header" size="mini">
              <el-table-column align="center" label="序号" type="index" width="50" />

              <el-table-column align="center" label="配送模式">
                <template #default="{row}">
                  {{ getLabel('distributor_mode', row.rddType) }}
                </template>
              </el-table-column>

              <el-table-column align="center" label="配送商" prop="distributeName" />

              <el-table-column align="center" label="配送费" prop="distributePrice">
                <template #default="{row}">
                  <div v-if="row.computeMode==='固定价格'">
                    <span v-if="row.distributePrice > 0">{{ isInteger(row.distributePrice) }}元</span>
                    <span v-if="sellUnit"> / {{ getLabel('sell_unit', sellUnit) }}</span>
                  </div>
                  <div v-if="row.computeMode==='终端价百分比'">
                    <span>{{ row.distributePrice }}%</span><span>终端价</span>
                  </div>
                </template>
              </el-table-column>

              <el-table-column align="center" label="配送服务编号" prop="distributeServeNo" />

              <el-table-column align="center" label="状态">
                <template #default="{row}">
                  <div v-if="row.updateType === 1 && row.rddStatus !== '1'" style="height: 20px;line-height: 20px">
                    <span>新增配送</span>
                  </div>
                  <div style="height: 20px;line-height: 20px">
                    {{ getLabel('distribute_status', row.rddStatus) }}
                  </div>
                </template>
              </el-table-column>

              <el-table-column align="center" label="是否取消配送">
                <template #default="scope">
                  <el-checkbox v-if="scope.row.rddStatus === '1'" v-model="scope.row.checked"
                    @change="(val)=>handlCheck(scope.row.checked,scope.$index)" />
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </template>

        <el-col :span="24">
          <item-title title="设置配送信息">
            <template #btn>
              <el-button class="border-btn" size="mini" @click="handlAdd">添加配送商</el-button>
            </template>
          </item-title>
        </el-col>

        <el-col :span="24">
          <el-table :data="openForm.tableData" border class="tableForm" header-cell-class-name="table-header"
            size="mini">
            <el-table-column align="center" label="序号" type="index" width="50" />
            <el-table-column align="center" label="配送模式">
              <template #default="scope">
                <el-form-item :prop="'tableData.' + scope.$index + '.rddType'"
                  :rules="{ required: true, message: '请选择配模式', trigger: 'change'}" label-width="0">
                  <el-select v-model="scope.row.rddType" placeholder="请选择配送模式" style="width: 100%"
                    @change="()=>handlRddtype(scope.row.rddType, scope.$index)">
                    <el-option v-for="item in distributionData" :key="item.id" :label="item.label"
                      :value="item.value" />
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>

            <el-table-column align="center" label="配送商">
              <template #default="scope">
                <el-form-item v-if="scope.row.rddType === '2'" :prop="'tableData.' + scope.$index + '.distributeName'"
                  :rules="{ required: true, message: '请选择配送商', trigger: 'change'}" label-width="0">
                  <el-autocomplete v-model="scope.row.distributeName" :fetch-suggestions="querySearchAsync"
                    placeholder="请选择配送商" placement="top" style="width: 100%"
                    @select="(val)=>handleSelect(val, scope.$index)">
                    <template #default="{ item }">
                      {{ item.distributeName }}
                    </template>
                  </el-autocomplete>
                </el-form-item>
              </template>
            </el-table-column>

            <el-table-column align="center" label="配送费">
              <template #default="scope">
                <!-- :rules="{ required: true, message: '请选择配送费', trigger: 'change'}" -->
                <el-form-item v-if="scope.row.rddType === '2'" :prop="'tableData.' + scope.$index + '.distributePrice'"
                  :rules="rules.distributePrice" label-width="0">
                  <shipping-popover ref="distributorsPopover" :agentProdoductId="agentProdoductId"
                    :distributors-data="distributorsData" :sell-unit="sellUnit" @confirm="feeConfirm">
                    <el-input v-model="scope.row.distributePrice" :disabled="scope.row.distributeName === ''"
                      class="inputSpan" clearable placeholder="请输入配送费" @clear="feetClear"
                      @focus="()=>handlFocus(scope.$index)">
                      <template #append>
                        <span v-if="scope.row.computeMode === '固定价格'">
                          元
                          <span v-if="sellUnit"> / {{ getLabel('sell_unit', sellUnit) }}</span>
                        </span>
                        <span v-if="scope.row.computeMode === '终端价百分比'">%终端价</span>
                      </template>
                    </el-input>
                  </shipping-popover>
                </el-form-item>
              </template>
            </el-table-column>

            <el-table-column align="center" label="配送服务编号" prop="distributeServeNo" />

            <el-table-column align="center" label="操作">
              <template #default="scope">
                <el-button v-if="scope.row.rddType !== '' && scope.row.distributeName !== ''
                    && scope.row.distributePrice !== '' && scope.row.distributeServeNo !== ''" type="text"
                  @click="handlEdit(scope.$index)">编辑
                </el-button>
                <el-button style="color: red" type="text" @click="handlDele(scope.$index)">删除</el-button>
              </template>

            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <div class="dialog-footer" style="display:flex;justify-content:center;align-items:center;">
        <el-button class="border-btn" size="small" style="margin-right: 20px;" @click="close">取消</el-button>
        <el-button class="main-btn" size="small" type="primary" @click="handlSubmit">提交审核</el-button>
      </div>
    </template>
  </el-dialog>

</template>

<script>
import { getCurrentInstance, inject, reactive, toRefs, nextTick } from "vue";
import { crmStore } from "@CRM/store";

export default {
  name: "SetiDelivery",
  props: {
    agentProdoductId: {
      type: Number,
      default: 0,
    },
    booleDis: {
      type: Boolean,
      default: true,
    },
    fineBool: {
      type: Boolean,
      default: true,
    },
    region: {
      type: Array,
      default: [],
    },
  },
  setup(props, context) {
    var validateDistributePrice = (rule, value, callback) => {
      var index = rule.field.split(".")[1];
      if (data.openForm.tableData[index].distributePrice === "") {
        callback(new Error("配送费为空"));
      } else {
        if (data.openForm.tableData[index].distributePrice === 0) {
          callback(new Error("配送费不能为0"));
        } else {
          callback();
        }
      }
    };

    const currentInstance = getCurrentInstance();
    const api = inject("api");
    var data = reactive({
      openForm: {
        value: "1",
        num: "",
        id: 0,
        tableData: [
          {
            id: 0, // 开发配送关系id
            devId: 0, // 开发id
            distributeServeNo: "",
            rddType: "1", // 配送分类 1 厂家  2 配送商
            distributeId: null, // 配送商ID
            distributeName: "", // 配送商NAMW
            distributeDetailId: null, // 配送服务ID
            distributeDetailName: "", // 配送nameID
            distributePrice: "", // 配送费
            sellUnit: "",
          },
        ],
      },
      queryParams: {},
      sellUnit: "",
      title: "设置配送信息",
      openBoole: false,
      rules: {
        distributePrice: [
          { validator: validateDistributePrice, trigger: "blur" },
        ],
      },
      openRef: null,
      distributionData:
        crmStore.getters["dictionary/getDictionary"]["distributor_mode"],
      distributorsList: [],
      distributorsData: {
        productId: 0, // 产品id
        distributeId: null, // 配送商id
        provinceCode: "", // 省code
        cityCode: "", // 市code
        areaCode: "", // 区code
      },
      index: null,
      distributorsPopover: null,
      distributeDeleteIds: [],
    });
    const close = () => {
      data.openBoole = false;
      remove();
    };

    const remove = () => {
      data.openRef.clearValidate();
      data.openRef.resetFields();
    };

    const open = (val, id) => {
      data.sellUnit = "";
      data.distributionData =
        crmStore.getters["dictionary/getDictionary"]["distributor_mode"];
      data.openForm = {
        value: "1",
        num: "",
        id: 0,
        tableData: [
          {
            id: 0, // 开发配送关系id
            devId: 0, // 开发id
            distributeServeNo: "",
            rddType: "1", // 配送分类 1 厂家  2 配送商
            distributeId: null, // 配送商ID
            distributeName: "", // 配送商NAMW
            distributeDetailId: null, // 配送服务ID
            distributeDetailName: "", // 配送nameID
            distributePrice: "", // 配送费
          },
        ],
      };
      data.openBoole = true;
      data.queryParams = val;
      data.sellUnit = val.sellUnit || val.productInfoDetail.sellUnit;
      data.distributorsData.productId = val.productId;
      data.distributorsData.provinceCode = val.provinceCode; // 省code
      data.distributorsData.cityCode = val.cityCode; // 市code
      data.distributorsData.areaCode = val.areaCode; // 区code
      data.openForm.id = id;
      if (data.queryParams.distributeContractDetails.length > 0) {
        data.queryParams.distributeContractDetails.forEach((item) => {
          item.checked = false;
        });
      }
      handlDisList();
    };

    const handlCheckId = () => {
      data.queryParams.distributeContractDetails.forEach((item) => {
        if (item.checked) {
          data.distributeDeleteIds.push(item.id);
        }
      });
    };

    const handlCheck = (val, index) => {
      data.queryParams.distributeContractDetails[index].checked = val;
      handlCheckId();
    };

    const handlAdd = () => {
      const a = {
        id: 0,
        devId: 0,
        distributeServeNo: "",
        rddType: "1",
        distributeId: null, // 配送商ID
        distributeName: "", // 配送商NAMW
        distributeDetailId: null, // 配送服务ID
        distributeDetailName: "", // 配送nameID
        distributePrice: "", // 配送费
        computeMode: "",
        sellUnit: "",
      };

      const aIndex = data.queryParams.distributeContractDetails.findIndex(
        (aa) => aa.rddType === "1"
      );
      const bIndex = data.openForm.tableData.findIndex(
        (aa) => aa.rddType === "1"
      );
      if (aIndex !== -1 || bIndex !== -1) {
        a.rddType = "2";
        data.openForm.tableData.push(a);
      } else {
        data.openForm.tableData.push(a);
      }
    };

    const handlEdit = () => {};

    const handlDele = (index) => {
      data.openForm.tableData.splice(index, 1);
    };

    const handlCancel = () => {};

    const feeConfirm = (val) => {
      data.openForm.tableData[data.index].computeMode = val.computeMode;
      data.openForm.tableData[data.index].distributePrice =
        val?.distributePrice || 0;
      data.openForm.tableData[data.index].distributeDetailName =
        val.distributeAbstract;
      data.openForm.tableData[data.index].distributeDetailId = val.id;
      data.openForm.tableData[data.index].distributeServeNo =
        val.distributeServeNo;
      if (Number(data.openForm.tableData[data.index].distributePrice) > 0) {
        var str = `tableData.${data.index}.distributePrice`;
        nextTick((_) => {
          data.openRef.clearValidate(str);
        });
      }
    };

    const handlFocus = (index) => {
      data.index = index;
      data.distributorsPopover.handlOpen();
    };

    const feetClear = () => {
      data.openForm.tableData[data.index].distributePrice = 0;
      data.openForm.tableData[data.index].computeMode = 0;
      data.openForm.tableData[data.index].distributeDetailName = "";
      data.openForm.tableData[data.index].distributeDetailId = 0;
      data.openForm.tableData[data.index].distributeServeNo = "";
    };

    const handlRddtype = (val, index) => {
      data.openForm.tableData[index].id = 0; // 开发配送关系id
      data.openForm.tableData[index].devId = 0; // 开发id
      data.openForm.tableData[index].distributeServeNo = "";
      data.openForm.tableData[index].distributeId = null; // 配送商ID
      data.openForm.tableData[index].distributeName = ""; // 配送商NAMW
      data.openForm.tableData[index].distributeDetailId = null; // 配送服务ID
      data.openForm.tableData[index].distributeDetailName = ""; // 配送nameID
      data.openForm.tableData[index].distributePrice = ""; // 配送费
      data.openForm.tableData[index].rddType = val;
    };

    const querySearchAsync = async (queryString, cb) => {
      let results1 = [],
        results2 = [];
      if (props.agentProdoductId === 0) {
        let res = await api.terminal.PRODUCT_PULLLIST(queryString);
        if (res.code === 0) {
          results1 = res.data.list || [];
        }
        cb(results1);
      } else {
        let ress = await api.marketingMatching.REGIONAL_DISTRIBUTION_PULLLIST(
          props.agentProdoductId
        );
        if (ress.code === 0) {
          results2 = ress.data || [];
        }
        cb(results2);
      }
    };

    const handlDisList = () => {
      const aIndex = data.queryParams.distributeContractDetails.findIndex(
        (aa) => aa.rddType === "1"
      );
      if (aIndex !== -1) {
        const a =
          crmStore.getters["dictionary/getDictionary"]["distributor_mode"];
        data.distributionData = a.filter((a) => a.value !== "1");
        data.openForm.tableData[0].rddType = "2";
      }
    };

    const handleSelect = (val, index) => {
      const aIndex = data.queryParams.distributeContractDetails.findIndex(
        (aa) => aa.distributeName === val.distributeName
      );
      if (aIndex !== -1) {
        currentInstance.proxy.customMessage({
          type: "error",
          message: "该配送商已设置",
        });
      } else {
        for (let i = 0; i < data.openForm.tableData.length; i++) {
          if (i !== index) {
            const a = data.openForm.tableData[i];
            if (a.distributeId === val.id) {
              currentInstance.proxy.customMessage({
                type: "error",
                message: "配送商重复",
              });
              break;
            } else {
              data.openForm.tableData[index].distributeName =
                val.distributeName;
              data.openForm.tableData[index].distributeId = val.id;
              data.openForm.tableData[index].distributeId = val.id;
              data.distributorsData.distributeId = val.id;
              data.openForm.tableData[index].distributePrice = "";
              data.openForm.tableData[index].distributeServeNo = "";
            }
          } else {
            data.openForm.tableData[index].distributeName = val.distributeName;
            data.openForm.tableData[index].distributeId = val.id;
            data.distributorsData.distributeId = val.id;
            data.openForm.tableData[index].distributePrice = "";
            data.openForm.tableData[index].distributeServeNo = "";
          }
        }
      }
      if (data.openForm.tableData[index].distributeName === "") {
        data.distributorsPopover.onCancel();
      }
    };

    const handlSubmit = () => {
      data.openForm.tableData.forEach((item) => {
        item.distributePrice = Number(item.distributePrice);
      });
      data.openRef.validate((valid) => {
        if (valid) {
          const distributeObj = {
            devId: data.openForm.id,
            distributeContractDetails: data.openForm.tableData,
            distributeDeleteIds: data.distributeDeleteIds,
          };
          if (
            data.openForm.tableData.length > 0 ||
            data.distributeDeleteIds.length > 0
          ) {
            api.terminal.PRODUCT_DISTRIBUTE(distributeObj).then((res) => {
              if (res.code === 0) {
                currentInstance.proxy.customMessage({
                  type: "success",
                  message: "配送商设置成功",
                });
                context.emit("distributeSuccsess");
                close();
              } else {
                currentInstance.proxy.customMessage({
                  type: "error",
                  message: res.msg,
                });
              }
            });
          } else {
            currentInstance.proxy.customMessage({
              type: "error",
              message: "配送商不能为空或者为设置配送信息",
            });
          }
        }
      });
    };

    return {
      ...toRefs(data),

      close,
      remove,
      open,
      handlSubmit,
      handlAdd,
      handlEdit,
      handlDele,
      feeConfirm,
      feetClear,
      querySearchAsync,
      handleSelect,
      handlFocus,
      handlCancel,
      handlCheck,
      handlCheckId,
      handlRddtype,
      handlDisList,
    };
  },
};
</script>

<style scoped>
/* @import url(); 引入css类 */

:deep(.tableForm .el-form-item--small.el-form-item) {
  margin-bottom: 0 !important;
}

.dialogForm {
  width: 100%;
  max-height: 600px;
  overflow-y: scroll;
}

:deep(.inputSpan .el-input-group__append) {
  padding: 0 2px 0 2px !important;
}
</style>